﻿#include "Timer.h"
#include "Misc.h"
#include <chrono>

namespace Base {

	Timer* Timer::s_Timer = nullptr;
	float Timer::s_delteTime = 0.0f;


	Timer::Timer() {
		if (s_Timer != nullptr)
		{
			Debug::ThrowOrMessageBox("s_Timer already init!");
		}
		s_Timer = this;

		m_lastTimeMs = GetMS();
	}

	void Timer::Tick() {
		auto curMs = GetMS();
		s_delteTime = (curMs - m_lastTimeMs) / 1000.0f;
		m_lastTimeMs = curMs;

		// 计算平均帧率
		++m_fpsCounter;
		m_totalTime += s_delteTime;
		if (m_totalTime >= 1.0f) {
			m_totalTime -= 1.0f;
			m_fps = m_fpsCounter;
			m_fpsCounter = 0;
		}
	}

	Timer::~Timer() {

	}


	// static
	LLong Timer::GetMS() {
		auto t0 = std::chrono::system_clock::now();
		auto t1 = std::chrono::time_point_cast<std::chrono::duration<LLong, std::milli>>(t0);
		return t1.time_since_epoch().count();
	}
}